package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.TokenHolder;
import com.itheima.constant.TokenConstant;
import com.itheima.domain.Employee;
import com.itheima.domain.User;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ClientInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    //在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String token=request.getHeader("AuthorizationUser");
        //通过token获取到存入的对象
        String user= (String) redisTemplate.opsForValue().get(TokenConstant.USER_TOKEN_PREFIX+token);
        User user1 = JSON.parseObject(user, User.class);
        assert user1 != null;
        System.out.println(user1);
        TokenHolder.setCurrentId(user1.getId());

       /* if (!StringUtils.hasText(user1)){
            response.getWriter().write(JSON.toJSONString(R.error("没有登录")));
            return false;
        }*/

        return true;
    }

    //在业务处理器处理器处理请求之后，生成视图之前被执行
    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("postHandle 运行了");
    }

    //在DispatcherService完全处理完请求之后被调用，可用于清理资源
    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion 运行了");
    }



}
